import ajax from "./promiseAjax.js";

let token = sessionStorage.getItem("token");
let showId = sessionStorage.getItem("show_id");
let dayTime = sessionStorage.getItem("day_time");
let startTime = sessionStorage.getItem("startTime");

let Name = document.querySelector(".userName");
let date = document.querySelector(".date");
let QRcode = document.querySelector(".QRcode");
let save = document.querySelector(".save");

let bookDayApi = "http://newshopapi.0melon0.cn/api/f_user/bookday";
let QrcodeApi = "http://newshopapi.0melon0.cn/api/f_user/Qrcode";
let bookDayData = {
  "token": token,
  "day_time": dayTime,
  "show_id": showId
}

ajax(bookDayApi, bookDayData, "POST").then(res => {
  let id = res.result.id;
  let userName = res.result.name;
  
  sessionStorage.setItem("userName", userName);

  //渲染用户名
  Name.innerHTML = userName;

  let QrcodeData = {
    "token": token,
    "id": id
  }

  ajax(QrcodeApi, QrcodeData, "GET").then(res => {
    // console.log(res.data.data);
    //渲染日期
    date.innerHTML = `${dayTime} ${startTime}`;
    //渲染二维码
    QRcode.innerHTML = `
      <img src="${res.data.data}" alt="">
    `;
    //保存二维码
    save.addEventListener("click", () => {
      let QRcodeURL = document.querySelector(".QRcode>img");
      downloadImg(QRcodeURL.src);
    })

    function downloadImg(url) {
      var a = document.createElement('a');          // 创建一个a节点插入的document
      var event = new MouseEvent('click')           // 模拟鼠标click点击事件
      a.download = '预约二维码'                  // 设置a节点的download属性值
      a.href = url;                                 // 将图片的src赋值给a节点的href
      a.dispatchEvent(event)                        // 触发鼠标点击事件
    }
  })
})

